package com.violet.repository.network.okhttp;

import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 设置头信息
 */
public class HeaderInterceptor implements Interceptor {

    private SharedPreferences mSp;

    public HeaderInterceptor(SharedPreferences sp) {
        mSp = sp;
    }

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        Request.Builder requestBuilder = originalRequest.newBuilder();
        Map<String, String> headers = getHeaders();
        if(headers != null && !headers.isEmpty()) {
            insertHeaders(headers, requestBuilder);
        }
        requestBuilder
                .addHeader("Accept-Encoding", "gzip")
                .addHeader("Accept", "application/json")
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .method(originalRequest.method(), originalRequest.body());
        requestBuilder.addHeader("Authorization", "Bearer " + "");//添加请求头信息，服务器进行token有效性验证
        String session = mSp.getString("session", "");
        if(!TextUtils.isEmpty(session)) {
            requestBuilder.addHeader("cookie", session);
        }
        Request request = requestBuilder.build();
        return chain.proceed(request);
    }

    private void insertHeaders(Map<String, String> maps, Request.Builder requestBuilder) {
         for(Map.Entry<String, String> entries: maps.entrySet()) {
             String key = entries.getKey();
             String value = entries.getValue();
             requestBuilder.addHeader(key, value);
         }
    }

    /**
     * 外部传入的header
     * @return
     */
    private Map<String, String> getHeaders() {
        String headers = mSp.getString("headers", "");
        if(TextUtils.isEmpty(headers)) return new HashMap<>();
        return new Gson().fromJson(headers, new TypeToken<HashMap<String,String>>(){}.getType());
    }
}
